<template>
  <el-select v-model="state" filterable remote reserve-keyword placeholder="请输入内容" :remote-method="querySearch"
    :loading="loading" @change="handleSelect">
    <el-option v-for="item in options" :key="item.productId" :label="item.title" :value="item.productId">
      <div class="name">{{ item.title }}</div>
      <span class="addr">商品Id：{{ item.productId }}</span>
    </el-option>
  </el-select>
</template>

<script>
export default {
  model: {
    prop: "value",
    event: "input",
  },
  props: {
    value: {
      type: Number,
      default: 0,
    },
  },

  data() {
    return {
      state: '',
      pageIndex: 1,
      pageSize: 10,
      loading: false,
      options: []
    };
  },

  methods: {
    // 获取数据列表
    async getDataList() {
      return await this.$http({
        url: this.$http.adornUrl('/product/product/list'),
        method: 'get',
        params: this.$http.adornParams({
          'key': this.state,
          'page': this.pageIndex,
          'limit': this.pageSize,
        })
      }).then(({ data }) => {
        console.log("获取商品列表成功", data);
        if (data && data.code === 200) {
          return data.page.list
        } else {
          return []
        }
      })
    },

    //获取商品详情
    async getCategoryList() {
      return await this.$http({
        url: this.$http.adornUrl('/product/product/info/' + this.value),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({ data }) => {
        console.log("获取商品数据成功", data);
        if (data && data.code === 200) {
          return data.product;
        }
      })
    },

    async querySearch(query) {
      if (query !== '') {
        this.loading = true;
        this.state = query;
        const result = await this.getDataList();
        this.options = result;
        this.loading = false;
      } else {
        this.options = [];
      }
    },

    handleSelect(val) {
      const selectedItem = this.options.find(item => item.productId === val);
      if (selectedItem) {
        this.$emit('input', selectedItem.productId)
        this.$emit('getProductTitle', selectedItem.title)
      }
    }
  },

  watch: {
    async value(newVal, oldVal) {
      if (newVal != 0) {
        const productItem = await this.getCategoryList()
        if (productItem) {
          this.state = productItem.productId
          this.options = [productItem]
          this.$emit('input', productItem.productId)
          this.$emit('getProductTitle', productItem.title)
        }
        return
      }

      this.state = ''
      this.options = []
      this.$emit('input', 0)
      this.$emit('getProductTitle', '')
    }
  }
}
</script>

<style lang="scss">
.el-select-dropdown__item {
  .name {
    text-overflow: ellipsis;
    overflow: hidden;
  }

  .addr {
    font-size: 12px;
    color: #b4b4b4;
  }
}
</style>
